<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
      <el-form-item label="年月" prop="monthYear">
        <el-date-picker clearable v-model="queryParams.monthYear" type="month" value-format="YYYY-MM" placeholder="请选择年月">
        </el-date-picker>
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option v-for="dict in audit_work_status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['audit:award:add']">新增</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['audit:award:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="awardList" @selection-change="handleSelectionChange" show-overflow-tooltip>
      <el-table-column label="序号" align="center" type="index" width="60" />
      <el-table-column label="收费站" align="center" prop="deptName" />
      <el-table-column label="年月" align="center" prop="monthYear" width="180">
      </el-table-column>
      <el-table-column label="查看附件" align="center" prop="allocatePlan">
        <template #default="scope">
          <el-button @click.stop="previewFun(scope.row.allocatePlan,scope.row.detailList,scope.row.checkList)" v-if="scope.row.allocatePlan">查看</el-button>
          <span v-else>暂无数据</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="明细表" align="center" prop="detailList">
        <template #default="scope">
          <el-button @click.stop="previewFun(scope.row.allocatePlan,scope.row.detailList,scope.row.checkList)" v-if="scope.row.detailList">查看</el-button>
          <span v-else>暂无数据</span>
        </template>
      </el-table-column>
      <el-table-column label="核对表" align="center" prop="checkList">
        <template #default="scope">
          <el-button @click.stop="previewFun(scope.row.allocatePlan,scope.row.detailList,scope.row.checkList)" v-if="scope.row.checkList">查看</el-button>
          <span v-else>暂无数据</span>
        </template>
      </el-table-column> -->
      <el-table-column label="上报人" align="center" prop="reporterName" />
      <el-table-column label="上报时间" align="center" prop="reportTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.reportTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="audit_work_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row,1)" v-hasPermi="['audit:award:approve']"
            v-if="scope.row.status!=4">审核</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['audit:award:edit']"
            v-if="scope.row.status!=4">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['audit:award:remove']"
            v-if="scope.row.status!=4">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改追缴奖励对话框 -->
    <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
      <el-form ref="awardRef" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="15">
          <el-col :span="12">
            <el-form-item label="收费站" prop="deptId">
              <el-tree-select style="width: 100%;" v-model="form.deptId" :data="deptOptions" :props="{ value: 'id', label: 'label', children: 'children' }"
                :disabled="isApproved" value-key="id" placeholder="请选择" check-strictly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="年月" prop="monthYear">
              <el-date-picker clearable style="width: 100%;" v-model="form.monthYear" type="month" value-format="YYYY-MM" placeholder="请选择年月"
                :disabled="isApproved">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分配方案" prop="allocatePlan">
              <file-upload v-model="form.allocatePlan" :disabled="isApproved" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="明细表" prop="detailList">
              <file-upload v-model="form.detailList" :disabled="isApproved" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="核对表" prop="checkList">
              <file-upload v-model="form.checkList" :disabled="isApproved" />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" :disabled="isApproved" :rows="5"  />
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="isApproved">
            <el-form-item label="是否同意" prop="isApproved">
              <el-radio-group v-model="form.isApproved">
                <el-radio :lvalue="1" :label="1">是</el-radio>
                <el-radio :lvalue="0" :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="isApproved">
            <el-form-item label="审批原因" prop="auditOpinion">
              <el-input v-model="form.auditOpinion" type="textarea" placeholder="请输入审批原因"  :rows="5" />
            </el-form-item>
          </el-col>

        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm" v-hasPermi="['audit:award:approve']" v-if="isApproved">确 定</el-button>
          <el-button type="primary" @click="submitForm" v-hasPermi="['audit:award:edit']" v-else>确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <Viewer ref="fileViewerRef" :dialog-doc="dialogDoc" dialogShowNum="3" dialogTitle="追缴奖励" :dialogArray="dialogArray" />
  </div>
</template>

<script setup name="Award">
import { listAward, getAward, delAward, addAward, updateAward, approve } from "@/api/charge/award";
import { deptTreeSelect } from "@/api/system/user";
import Viewer from "@/components/Custom/viewerContrast.vue";
import useUserStore from '@/store/modules/user'


const { proxy } = getCurrentInstance();
const { audit_work_status } = proxy.useDict('audit_work_status');
const userStore = useUserStore()
const awardList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const dialogDoc = ref(false)
const fileViewerRef = ref(null);
const deptOptions = ref()
const deptId = ref()
const isApproved = ref(false)
const dialogArray = ref([])

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    deptId: null,
  },
  rules: {
    deptId: [
      { required: true, message: "收费站不能为空", trigger: "blur" }
    ],
    monthYear: [
      { required: true, message: "年月不能为空", trigger: "blur" }
    ],
    allocatePlan: [
      { required: true, message: "分配方案不能为空", trigger: "blur" }
    ],
    detailList: [
      { required: true, message: "明细表不能为空", trigger: "blur" }
    ],
    checkList: [
      { required: true, message: "核对表不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

function getDeptTree() {
  deptTreeSelect().then(response => {
    deptOptions.value = response.data;
  });
};

/** 查询追缴奖励列表 */
function getList() {
  loading.value = true;
  listAward(queryParams.value).then(response => {
    awardList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
  };
  proxy.resetForm("awardRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  form.value.deptId = deptId.value;
  isApproved.value = false;
  title.value = "添加追缴奖励";
}

/** 修改按钮操作 */
function handleUpdate(row, type) {
  reset();
  if (type == 1) {
    isApproved.value = true;
  } else {
    isApproved.value = false;
  }
  const _id = row.id || ids.value
  getAward(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = type != 1 ? "修改追缴奖励" : "审核追缴奖励";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["awardRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        if (isApproved.value) {
          // 审批
          approve({ isApproved: form.value.isApproved, auditOpinion: form.value.auditOpinion, id: form.value.id }).then(response => {
            proxy.$modal.msgSuccess("审批成功");
            open.value = false;
            getList();
          });
        } else {
          updateAward(form.value).then(response => {
            proxy.$modal.msgSuccess("修改成功");
            open.value = false;
            getList();
          });
        }

      } else {
        addAward(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除追缴奖励编号为"' + _ids + '"的数据项？').then(function () {
    return delAward(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('audit/award/export', {
    ...queryParams.value
  }, `追缴奖励_${new Date().getTime()}.xlsx`)
}
// 预览
const previewFun = async (file1, file2, file3) => {
  dialogArray.value = []
  const baseUrl = import.meta.env.VITE_APP_BASE_API;
  let arrFile = [file1, file2, file3];
  let data = {};
  let arr = [];
  let suffix = ''
  let nameArr = ''
  arrFile.forEach((item,index) => {
    if (item) {
      data.src = `${baseUrl}${item}`;
      arr = item.split(".");
      suffix = arr[arr.length - 1];
      nameArr = item.split("/");
      dialogArray.value.push({ ...data, ...{ suffix: suffix, nameNew: nameArr[nameArr.length - 1],title:index==0?'分配方案':index==1?'明细表':'核对表' } })
    }
  })
  dialogDoc.value = true;



};

const getDeptId = () => {
  userStore.getInfo().then(res => {
    if (res.code == 200) {
      deptId.value = res.user.dept.deptId;

      getList()
    }

  })
}

getDeptTree()
getDeptId()
</script>

<style scoped>
.padding-left {
  padding-left: 120px;
  font-size: 12px;
  color: red;
}
</style>
